package com.rech.xbexpress3;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutCompat;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.rech.utils.OtherUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class Jj2Activity extends AppCompatActivity {
    /**
     * Whether or not the system UI should be auto-hidden after
     * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
     */
    private static final boolean AUTO_HIDE = true;
    private int mExpType = 0;
    private String boxValue = "[{}]";
    private TextView djs ;
    private Timer countTimer;
    private long jj2_clicktime = 0;
    private int jjcount = 100;
    public static final long TIME_INTERVAL = 3000L;


    /**
     * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
     * user interaction before hiding the system UI.
     */
    private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

    /**
     * Some older devices needs a small delay between UI widget updates
     * and a change of the status and navigation bar.
     */
    private static final int UI_ANIMATION_DELAY = 300;
    private final Handler mHideHandler = new Handler();

    private final Runnable mHidePart2Runnable = new Runnable() {
        @SuppressLint("InlinedApi")
        @Override
        public void run() {
            // Delayed removal of status and navigation bar


        }
    };

    private final Runnable mShowPart2Runnable = new Runnable() {
        @Override
        public void run() {

        }
    };
    private boolean mVisible;
    private final Runnable mHideRunnable = new Runnable() {
        @Override
        public void run() {
            hide();
        }
    };
    /**
     * Touch listener to use for in-layout UI controls to delay hiding the
     * system UI. This is to prevent the jarring behavior of controls going away
     * while interacting with activity UI.
     */
    private final View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (AUTO_HIDE) {
                delayedHide(AUTO_HIDE_DELAY_MILLIS);
            }
            return false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedPreferences sharedPreferences = getSharedPreferences("xbbox", Context.MODE_PRIVATE);
        String orientation = sharedPreferences.getString("Orientation","");
        if (orientation.equals("landscape")) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }

        jjcount = 100;
        //eventbus
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        setContentView(R.layout.activity_jj2);
        djs = findViewById(R.id.jj2_djs);
        mVisible = true;
        getSupportActionBar().hide();
        new FetchGetBoxStateTask().execute();
        Button jj2_back = (Button) findViewById(R.id.jj2_back);
        jj2_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long nowTime = System.currentTimeMillis();

                if (nowTime - jj2_clicktime > TIME_INTERVAL) {
                    jj2_clicktime = nowTime;
                    Intent intent = new Intent();
                    //intent.putExtra("sn", resultString);
                    setResult(1003, intent);
                    Exit();
                    finish();

                }
                //startActivity(new Intent(FullscreenActivity.this, FaceActivity.class));
            }
        });
//        Button jj2_next = (Button) findViewById(R.id.jj2_next);
//        jj2_next.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if(mExpType == 0){
//                    Toast.makeText(Jj2Activity.this, "请选择快递类型", Toast.LENGTH_SHORT).show();
//                    return ;
//                }
//                SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();
//                editor.putInt("jj_exp",mExpType);
//                editor.putString("jj_boxvalue",boxValue);
//                editor.apply();
//
//                Intent intent = new Intent();
//                //intent.putExtra("sn", resultString);
//                setResult(1004, intent);
//                finish();
//                //startActivity(new Intent(FullscreenActivity.this, FaceActivity.class));
//            }
//        });
        final Button kd_img = (Button)findViewById(R.id.jj2_kd_img);
        final Button cn_img = (Button)findViewById(R.id.jj2_cn_img);
        kd_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                kd_img.setClickable(false);
                //kd_img.setBackgroundColor(android.graphics.Color.parseColor("#ffffff"));
                long nowTime = System.currentTimeMillis();

                if (nowTime - jj2_clicktime > TIME_INTERVAL) {
                    jj2_clicktime = nowTime;
                    mExpType = 1;
                    SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();
                    editor.putInt("jj_exp",mExpType);
                    editor.putString("jj_boxvalue",boxValue);
                    editor.apply();

                    Intent intent = new Intent();
                    //intent.putExtra("sn", resultString);
                    setResult(1004, intent);
                    Exit();
                    finish();

                }
            }
        });

        cn_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cn_img.setClickable(false);
                long nowTime = System.currentTimeMillis();

                if (nowTime - jj2_clicktime > TIME_INTERVAL) {
                    jj2_clicktime = nowTime;
                    mExpType = 2;
                    SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();
                    editor.putInt("jj_exp",mExpType);
                    editor.putString("jj_boxvalue",boxValue);
                    editor.apply();

                    Intent intent = new Intent();
                    //intent.putExtra("sn", resultString);
                    setResult(1004, intent);
                    Exit();
                    finish();

                }
            }
        });


        countTimer=new Timer();
        countTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                jjcount--;
                Message message = new Message();
                message.what=20000;
                EventBus.getDefault().post(message);
                if(jjcount < 1){
                    //OtherUtil.restartApplication(Jj2Activity.this);
                    Exit();
                    finish();
                }
            }
        },0,1000);
    }
    private void Exit(){
        countTimer.cancel();
        EventBus.getDefault().unregister(this);
    }
    @Override
    protected void onDestroy() {

        super.onDestroy();
    }
    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        // Trigger the initial hide() shortly after the activity has been
        // created, to briefly hint to the user that UI controls
        // are available.
        delayedHide(100);
    }

    private void toggle() {
        if (mVisible) {
            hide();
        } else {
            show();
        }
    }

    private void hide() {
        // Hide UI first
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        mVisible = false;


    }

    @SuppressLint("InlinedApi")
    private void show() {
        // Show the system bar
        mVisible = true;


    }

    /**
     * Schedules a call to hide() in delay milliseconds, canceling any
     * previously scheduled calls.
     */
    private void delayedHide(int delayMillis) {
        mHideHandler.removeCallbacks(mHideRunnable);
        mHideHandler.postDelayed(mHideRunnable, delayMillis);
    }
    @Subscribe(threadMode = ThreadMode.MAIN,priority = 100,sticky = false)     //在UI线程执行，100  为优先级
    public void onEvent(Message message){
        Intent intent = new Intent();
        switch(message.what){
            case 10106:
                handleBoxStateTask(message.obj);
                break;
            case 10107:
                Toast.makeText(Jj2Activity.this, "获取柜子状态失败", Toast.LENGTH_SHORT).show();
                break;
            case 20000:
                handleDJS();
                break;

        }
    }
    private void handleDJS(){
        djs.setText(String.valueOf(jjcount));
    }
    public void handleBoxStateTask(Object obj) {
        try{
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
                JSONArray orders = result.getJSONArray("data");
                boxValue = orders.toString();
                for(int i=0; i<orders.length(); i++){
                    JSONObject jsonObject1 = orders.getJSONObject(i);
                    String itemId = jsonObject1.get("id").toString();
                    String itemName = jsonObject1.get("name").toString();
                    String itemType = jsonObject1.get("type").toString();
                    String itemCount = jsonObject1.get("count").toString();

                    String nameId = "jj2_name"+String.valueOf(i+1);
                    String countId = "jj2_count"+String.valueOf(i+1);
                    String layoutId = "jj2_box"+String.valueOf(i+1);
                    ((TextView)findViewById(OtherUtil.getResId(nameId,R.id.class))).setText(itemName);
                    ((TextView)findViewById(OtherUtil.getResId(countId,R.id.class))).setText(itemCount);
                    findViewById(OtherUtil.getResId(layoutId,R.id.class)).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.WRAP_CONTENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 1));


                }


            }
        }
        catch (Exception e){
            Log.d("Grid",e.toString());
        }
    }
}
